package com.neolix.watch;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.neolix.watch.adapter.RemindEventAdapter;
import com.neolix.watch.bluetooth.BlueToothUtil;
import com.neolix.watch.dao.RemindEvent;
import com.neolix.watch.domain.RemindEventViewModel;
import com.neolix.watch.util.Constant;
import com.neolix.watch.util.RunTimeDatabaseHelper;

import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.List;

import static com.neolix.watch.NeolixApplication.getInstance;
import static com.neolix.watch.util.JsonConverter.convertObjectToJson;
import static com.neolix.watch.util.StringUtil.formatTemplateString;
import static com.neolix.watch.util.StringUtil.showText;

public class RemindActivity extends NeolixNaviagationBaseActivity {

    public static final int REQUEST_ADD_REMIND_EVENT_CODE = 1;
    public static final int REQUEST_EDIT_EVENT_CODE = 2;
    private ListView listView;
    private List<RemindEvent> remindEvents;
    private RemindEventAdapter adapter;
    private RunTimeDatabaseHelper databaseHelper;

    public RemindActivity() {
        super(R.layout.activity_remind);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(getString(R.string.remind_event));
        setRightButton(R.drawable.selector_add);

        listView = (ListView) findViewById(R.id.remind_event_list);
        initData();

        setRightButtonClickedListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (remindEvents.size() >= Constant.MAX_REMIND_EVENT) {
                    showText(formatTemplateString(R.string.tips_remind_event_count, Constant.MAX_REMIND_EVENT));
                    return;
                }

                Intent intent = new Intent(getApplicationContext(), AddRemindActivity.class);
                intent.putExtra(Constant.EVENT_ID, getRemindEventID());
                startActivityForResult(intent, REQUEST_ADD_REMIND_EVENT_CODE);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                editRemindEvent(i);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ADD_REMIND_EVENT_CODE && resultCode == RESULT_OK) {
            loadRemainEvent();
        } else if (requestCode == REQUEST_EDIT_EVENT_CODE && resultCode == RESULT_OK) {
            loadRemainEvent();
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflater = new MenuInflater(this);
        inflater.inflate(R.menu.menu, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        item.setChecked(true);

        final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.edit_menu:
                if (info != null) {
                    editRemindEvent(info.position);
                }
                break;
            case R.id.delete_menu:
                if (info != null) {
                    //TODO 发送到手表
                    RemindEvent event = remindEvents.get(info.position);
                    if (getInstance().isConnectWatch()) {
                        BlueToothUtil.syncRemindEvent(1, event);
                        databaseHelper.deleteRemindEvent(event);
                        loadRemainEvent();
                    } else {
                        showText(getString(R.string.delete_remind_event_failure));
                    }
                }
                break;
        }
        return super.onContextItemSelected(item);
    }

    private void editRemindEvent(int position) {
        Intent intent = new Intent(getApplicationContext(), AddRemindActivity.class);
        intent.putExtra(Constant.REMIND_EVENT_VIEW_MODEL, convertObjectToJson(adapter.getItem(position)));
        startActivityForResult(intent, REQUEST_EDIT_EVENT_CODE);
    }

    private void initData() {
        databaseHelper = RunTimeDatabaseHelper.initial(getApplicationContext());
        adapter = new RemindEventAdapter(getApplicationContext());
        adapter.bindListView(listView);

        loadRemainEvent();
    }

    private void loadRemainEvent() {
        DateTime now = DateTime.now();
        databaseHelper.deleteRemindEventLessThan(now);
        remindEvents = databaseHelper.queryRemindEventGreaterThanOrEqualTo(now);
        if (remindEvents != null && remindEvents.size() != 0)
            registerForContextMenu(listView);
        else
            unregisterForContextMenu(listView);

        adapter.setData(getViewModel(remindEvents));
    }

    private List<RemindEventViewModel> getViewModel(List<RemindEvent> remindEvents) {
        List<RemindEventViewModel> models = new ArrayList<RemindEventViewModel>();
        if (remindEvents == null || remindEvents.size() == 0) {
            RemindEventViewModel model = new RemindEventViewModel(null, -1, null, null, null);
            models.add(model);
        } else {
            for (RemindEvent event : remindEvents) {
                RemindEventViewModel model = new RemindEventViewModel(event.getId(), event.getEventID(), event.getContent(),
                        event.getDateTime(), event.getCreateDateTime());
                models.add(model);
            }
        }
        return models;
    }

    private int getRemindEventID() {
        int index = 0;
        List<Integer> allConllect = new ArrayList<Integer>();
        List<Integer> useConllect = new ArrayList<Integer>();
        if (remindEvents != null && remindEvents.size() > 0) {
            for (int i = 0; i < Constant.MAX_REMIND_EVENT; i++) {
                allConllect.add(i);
            }

            for (int j = 0; j < remindEvents.size(); j++) {
                useConllect.add(remindEvents.get(j).getEventID());
            }

            allConllect.removeAll(useConllect);
            index = allConllect.get(0);
        }

        return index;
    }
}
